package com.jgit;

/**
 * Tree对象中的条目
 */
public class TreeEntry {
    private String mode;  // 文件模式（如 "100644" 表示普通文件）
    private String name;  // 文件名或目录名
    private String hash;  // 指向的对象的SHA-1哈希
    
    public TreeEntry(String mode, String name, String hash) {
        this.mode = mode;
        this.name = name;
        this.hash = hash;
    }
    
    public String getMode() {
        return mode;
    }
    
    public String getName() {
        return name;
    }
    
    public String getHash() {
        return hash;
    }
    
    public byte[] toBytes() {
        String entry = mode + " " + name + "\0";
        byte[] entryBytes = entry.getBytes();
        byte[] hashBytes = hexToBytes(hash);
        byte[] result = new byte[entryBytes.length + hashBytes.length];
        System.arraycopy(entryBytes, 0, result, 0, entryBytes.length);
        System.arraycopy(hashBytes, 0, result, entryBytes.length, hashBytes.length);
        return result;
    }
    
    public static TreeEntry fromBytes(byte[] data, int offset) {
        // 找到第一个null字节（分隔符）
        int nullIndex = -1;
        for (int i = offset; i < data.length; i++) {
            if (data[i] == 0) {
                nullIndex = i;
                break;
            }
        }
        
        if (nullIndex == -1) {
            throw new IllegalArgumentException("Invalid tree entry format");
        }
        
        String header = new String(data, offset, nullIndex - offset);
        String[] parts = header.split(" ", 2);
        String mode = parts[0];
        String name = parts[1];
        
        // 读取20字节的SHA-1哈希
        byte[] hashBytes = new byte[20];
        System.arraycopy(data, nullIndex + 1, hashBytes, 0, 20);
        String hash = bytesToHex(hashBytes);
        
        return new TreeEntry(mode, name, hash);
    }
    
    private static byte[] hexToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                                 + Character.digit(hex.charAt(i+1), 16));
        }
        return data;
    }
    
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

